<?php
/**
 * 零起飞-(07FLY-CRM)
 * ==============================================
 * 版权所有 2015-2028   成都零起飞网络，并保留所有权利。
 * 网站地址: http://www.07fly.xyz
 * ----------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ==============================================
 * OaReimburseor: kfrs <goodkfrs@QQ.com> 574249366
 * Date: 2019-10-3
 */

namespace app\workflow\logic;

use app\common\logic\TableField;

/**
 * 报销单分类管理=》逻辑层
 */
class OaReimburse extends WorkflowBase
{
    /**
     * 报销单分类列表
     * @param array $where
     * @param bool $field
     * @param string $order
     * @param int|mixed $paginate
     * @return
     */
    public function getOaReimburseList($where = [], $field = true, $order = 'sort asc', $paginate = DB_LIST_ROWS)
    {
        $list= $this->modelOaReimburse->getList($where, $field, $order, $paginate)->toArray();
		if($paginate===false) $list['data']=$list;
        foreach ($list['data'] as $key=>&$row){
			$row['handle_user_name']=$this->modelSysUser->getValue(['id'=>$row['handle_user_id']],'realname');
			$row['audit_user_name']=$this->modelSysUser->getValue(['id'=>$row['audit_user_id']],'realname');
			$row['create_user_name']=$this->modelSysUser->getValue(['id'=>$row['create_user_id']],'realname');
			$row['status_arr']=$this->modelOaReimburse->status($row['status']);
		}
        return $list;
    }

    /**
     * 报销单分类添加
     * @param array $data
     * @return array
     */
    public function oaReimburseAdd($data = [])
    {

        $validate_result = $this->validateOaReimburse->scene('add')->check($data);
        if (!$validate_result) {
            return [RESULT_ERROR, $this->validateOaReimburse->getError()];
        }

        if($data['total_money']<=0){
			return [RESULT_ERROR, '报销明细不能为空或者为0'];
		}

        $reimData=[
        	'id'=>$data['id'],
        	'name'=>$data['name'],
        	'money'=>$data['total_money'],
        	'handle_user_id'=>$data['handle_user_id'],
        	'create_user_id'=>empty($data['create_user_id'])?SYS_USER_ID:$data['create_user_id'],
		];
		$reimburse_id = $this->modelOaReimburse->setInfo($reimData);

		foreach ($data['fy_money'] as $key=>$row){
			$listData[]=[
				'reimburse_id'=>$reimburse_id,
				'name'=>$data['fy_name'][$key],
				'money'=>$data['fy_money'][$key],
				'remark'=>$data['fy_remark'][$key],
				'type_name'=>$data['fy_type_name'][$key],
				'handle_date'=>$data['fy_handle_date'][$key],
			];
		}
		$result = $this->modelOaReimburseList->setList($listData);

        $url = url('show');
        $result && action_log('新增', '新增报销单：' . $data['name']);

        return $result ? [RESULT_SUCCESS, '添加成功', $url] : [RESULT_ERROR, $this->modelOaReimburse->getError()];
    }

    /**
     * 报销单分类编辑
     * @param array $data
     * @return array
     */
    public function oaReimburseEdit($data = [])
    {

        $validate_result = $this->validateOaReimburse->scene('edit')->check($data);
        if (!$validate_result) {
            return [RESULT_ERROR, $this->validateOaReimburse->getError()];
        }

		if($data['total_money']<=0 || empty($data['fy_money'])){
			return [RESULT_ERROR, '报销明细不能为空或者为0'];
		}

		$reimData=[
			'id'=>$data['id'],
			'status'=>0,//修改审核初始状态
			'name'=>$data['name'],
			'money'=>$data['total_money'],
			'handle_user_id'=>$data['handle_user_id'],
			'create_user_id'=>empty($data['create_user_id'])?SYS_USER_ID:$data['create_user_id'],
		];
		$result = $this->modelOaReimburse->setInfo($reimData);

		//删除记录
		$this->modelOaReimburseList->deleteInfo(['reimburse_id'=>$data['id']],true);
		foreach ($data['fy_money'] as $key=>$row){
			$listData[]=[
				'reimburse_id'=>$data['id'],
				'name'=>$data['fy_name'][$key],
				'money'=>$data['fy_money'][$key],
				'remark'=>$data['fy_remark'][$key],
				'type_name'=>$data['fy_type_name'][$key],
				'handle_date'=>$data['fy_handle_date'][$key],
			];
		}
		$result = $this->modelOaReimburseList->setList($listData);

        $result && action_log('编辑', '编辑报销单，name：' . $data['name']);
		$url = url('show');
        return $result ? [RESULT_SUCCESS, '编辑成功', $url] : [RESULT_ERROR, $this->modelOaReimburse->getError()];
    }

    /**
     * 报销单分类删除
     * @param array $where
     * @return array
     */
    public function oaReimburseDel($data = [])
    {

    	$where['id']=['in',$data['id']];
        $result = $this->modelOaReimburse->deleteInfo($where,true);

		$map['reimburse_id']=['in',$data['id']];
		$result  &&  $this->modelOaReimburseList->deleteInfo($map,true);

        $result && action_log('删除', '删除报销单分类，where：' . http_build_query($where));

        return $result ? [RESULT_SUCCESS, '删除成功'] : [RESULT_ERROR, $this->modelOaReimburse->getError()];
    }

    /**报销单分类信息
     * @param array $where
     * @param bool $field
     * @return
     */
    public function getOaReimburseInfo($where = [], $field = true)
    {
        $info= $this->modelOaReimburse->getInfo($where, $field);
        $info['reimburse_list']=$this->modelOaReimburseList->getList(['reimburse_id'=>$info['id']],'','',false);
        $info['handle_user_name']=$this->modelSysUser->getValue(['id'=>$info['handle_user_id']],'realname');
        $info['audit_user_name']=$this->modelSysUser->getValue(['id'=>$info['audit_user_id']],'realname');
        $info['status_arr']=$this->modelOaReimburse->status($info['status']);
        return $info;
    }

    /**报销单分类信息
     * @param array $where
     * @param bool $field
     * @return
     */
    public function getOaReimburseOneName($id=0)
    {

        $data= $this->modelOaReimburse->getValue(['id'=>$id],'name');
        return $data;
    }

	/**报销单分=>类型
	 * @param array $where
	 * @param bool $field
	 * @return
	 */
	public function getOaReimburseType($key='')
	{
		return $this->modelOaReimburse->type($key);
	}

	/**报销单分=>类型
	 * @param array $where
	 * @param bool $field
	 * @return
	 */
	public function getStatus($key='')
	{
		return $this->modelOaReimburse->status($key);
	}

    /**
     * 获取列表搜索条件
     */
    public function getWhere($data = [])
    {

        $where = [];
        //关键字查
        !empty($data['keywords']) && $where['name|remark'] = ['like', '%'.$data['keywords'].'%'];

		//创建时间
		if(!empty($data['handle_date'])){
			$range_date=str2arr($data['handle_date'],"-");
			$where['handle_date'] = ['between', $range_date];
		}
		//审核时间
		if(!empty($data['audit_time'])){
			$range_date=str2arr($data['audit_time'],"-");
			$where['audit_time'] = ['between', $range_date];
		}

        return $where;
    }

    /**
     * 获取排序条件
     */
    public function getOrderBy($data = [])
    {
        $order_by="";
        //排序操作
        if(!empty($data['orderField'])){
            $orderField = $data['orderField'];
            $orderDirection = $data['orderDirection'];
        }else{
            $orderField="";
            $orderDirection="";
        }
        if($orderField=='by_name'){
            $order_by ="name $orderDirection";
        }else{
            $order_by ="create_time asc";
        }
        return $order_by;
    }


	/**
	 * 回款管理=》审核
	 * 1、添加资金流水，2、更新业务订单 3、更新财务订单
	 * @param array $data
	 * @return array
	 */
	public function oaReimburseAudit($data = [])
	{
		$where['id']=['=',$data['id']];
		//$info=$this->modelOaReimburse->getInfo(['id'=>$data['id']]);

		$updata=[
			'status'=>$data['status'],
			'audit_remark'=>$data['audit_remark'],
			'audit_user_id'=>SYS_USER_ID,
			'audit_time'=>format_time(),
		];
		$result = $this->modelOaReimburse->updateinfo($where,$updata);
		$url = url('show');
		$result && action_log('审核', '审核回款管理，name：' . $data['id']);
		return $result ? [RESULT_SUCCESS, '操作成功', $url] : [RESULT_ERROR, $this->modelOaReimburse->getError()];
	}


	/**
	 * 报销申请=》更新状态
	 * @param array $data
	 * @return array
	 * Author: kfrs <goodkfrs@QQ.com> created by at 2020/9/18 0018
	 */
	public function setOaReimburseStatus($data = [])
	{
		if (empty($data['status']) || empty($data['id'])) {
			return [RESULT_ERROR, '参数status不能为空'];
			exit;
		}
		$result = $this->modelOaReimburse->setFieldValue(['id' => $data['id']], 'status', $data['status']);
		$result && action_log('编辑', '报销状态' . $data['id']);
		return $result ? [RESULT_SUCCESS, '编辑成功', ''] : [RESULT_ERROR, $this->modelSalOrder->getError()];
	}

	/**
	 * 报销申请=》审核提交
	 * @param array $data
	 * @return array
	 * Author: kfrs <goodkfrs@QQ.com> created by at 2020/9/18 0018
	 */
	public function setOaReimburseAuditSend($data = [])
	{
		if (empty($data['status']) || empty($data['id'])) {
			return [RESULT_ERROR, '参数status不能为空'];
			exit;
		}

		//发起流程审核
		$intedata['business_type']='oa_reimburse';
		$intedata['business_id']=$data['id'];

		$res=$this->logicWorkflowBusiness->workflowAddInterface($intedata);
		if ($res[0] == RESULT_ERROR) return $res;

		$result = $this->modelOaReimburse->setFieldValue(['id' => $data['id']], 'status', $data['status']);

		$result && action_log('提交', '提交报销审核：' . $data['id']);
		return $result ? [RESULT_SUCCESS, '提交报销审核', ''] : [RESULT_ERROR, $this->modelSalOrder->getError()];
	}

    /**
     * 报销申请=》审核提交
     * @param array $data
     * @return array
     * Author: kfrs <goodkfrs@QQ.com> created by at 2020/9/18 0018
     */
    public function setAuditSend($data = [])
    {
        if (empty($data['workflow_id']) || empty($data['id'])) {
            return [RESULT_ERROR, '选择申请流程不能为空'];
            exit;
        }
        //内部接口调用=》提交看审批
        $intedata['business_type']='oa_reimburse';
        $intedata['business_id']=$data['id'];
        $intedata['workflow_id']=$data['workflow_id'];
        $intedata['apply_user_id']=SYS_USER_ID;//业务申请人员
        $intedata['create_user_id']=SYS_USER_ID;//创建人员
        $rpcurl=url('workflow/rpc.RpcApi/workFlowBusinessAdd',$intedata);
        $res=httpRpc($rpcurl);

        if ($res['code'] == DATA_ERROR) return [RESULT_ERROR, $res['msg'], ''];

        $result = $this->modelOaReimburse->setFieldValue(['id' => $data['id']], 'status', 1);

        $result && action_log('提交', '提交请假审核：' . $data['id']);
        return $result ? [RESULT_SUCCESS, '提交请假审核', ''] : [RESULT_ERROR, $this->modelOaReimburse->getError()];
    }

    /**
     * 报销申请=》取消审批状态
     * @param array $data
     * @return array
     * Author: kfrs <goodkfrs@QQ.com> created by at 2020/9/18 0018
     */
    public function setAuditCancel($data = [])
    {
        if (empty($data['status']) || empty($data['id'])) {
            return [RESULT_ERROR, '参数status不能为空'];
            exit;
        }

        $result = $this->modelOaReimburse->setFieldValue(['id' => $data['id']], 'status', $data['status']);

        $result && action_log('撤消', '取消请假审批：' . $data['id']);
        return $result ? [RESULT_SUCCESS, '编辑成功', ''] : [RESULT_ERROR, $this->modelOaReimburse->getError()];
    }

}
